const fs = require('fs');
const path = require('path');
const { ErrorModel, SuccessModel } = require('../../model/responseMode');
const MusicListModel = require('../../model/music/musicListModel');
const MusicLrcTextSchema = require('../../model/music/musicTextModel');
// 获取src的绝对路径
let absolutePath = fs.realpathSync('src')

const addMusicList = () => {
  let musicList = []
  const data = fs.readdirSync("./src/statics/music");
  data.forEach(async item => {
    let index = item.lastIndexOf('.');
    let name = item.substring(0, index);
    let list = name.split(` - `);
    let singer = list[0].trim();    // 歌手
    let songName = list[1].trim();  // 歌曲
    let fileType = item.substring(index, item.length);  // 文件类型
    let path = 'statics/music/';
    let original = item
    let obj = {
      singer,
      music_name: songName,
      music_lrc: name,
      file_type: fileType,
      path,
      original
    }
    // 将音乐入库
    music = new MusicListModel(obj)
    try {
      await music.save()
    } catch (error) {
      console.log(error)
    }
  })
  return musicList
}

const updataMusicList = async () => {
  try {
    let data = null
    // await MusicListModel.updateMany({$set: {"path": "statics/music/" }});
    // data= await MusicListModel.updateOne({ _id: '646efc486afd30338c955e26' }, {$set:{ 'music_name': 'aaaa' }});
    return {
      data
    }
  } catch (error) {
    console.log(error);
  }
  return {
    message: 'ok'
  }
}

const getMusicList = async (query) => {
  let data = query.value
  // 返回歌曲列表
  let musicList = []
  try {
    // 如果有参数
    if(data){
      const regex = new RegExp(data, 'i');
      musicList = await MusicListModel.find({$or: [
        { singer: regex },
        { music_name: regex },
      ]}).select('singer music_name');
    }else{
      musicList = await MusicListModel.find().select('singer music_name');
    }
  } catch (error) {
    return new ErrorModel('错误')
    musicList = []
  }

  if(musicList.length == 0){
    return new ErrorModel([], '没有找到包含字符的歌曲或歌手')
  }
  return new SuccessModel(musicList, '获取成功')
}

const getMusicItem = async (query) => {
  let search = Object.keys(query)
  if(search.length == 0){
    return new ErrorModel('请搜索歌曲或者歌手');
  }

  let song = null
  if(query['_id']){
    try {
      song = await MusicListModel.findOne({_id: query['_id']}, { _id: false }).select('path music_name music_lrc original');
      lrc = await MusicLrcTextSchema.findOne({name: song.music_lrc}, { _id: false }).select('text')
    } catch (error) {
      console.log(error);
    }
    
    if(song == null){
      return new ErrorModel('没有找到资源');
    }

    // 获取文件目录
    const filesPath = fs.realpathSync(`${absolutePath}/${song.path}`);
    // 拼接文件路径
    const filePath = path.join(filesPath, song.original);
    try {
      // 是否有此文件
      fs.openSync(filePath)
      let base64data = fs.readFileSync(filePath).toString('base64');
      let data = {
        base64: base64data,
        music_lrc: lrc,
        music_name: song.music_name
      }
      return new SuccessModel(data, '获取音乐文件成功')
    } catch (error) {
      return new ErrorModel('没有找到搜索歌曲')
    }
  }
}

module.exports = {
  getMusicList,
  getMusicItem,
  addMusicList,
  updataMusicList
}